package day28;

/**
 * @author aiPlusPlus
 * @version 1.0
 * @date 2022/11/28 17:57
 */

/**
 * 给定一个字符串 s，你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
 *
 *
 *
 * 示例 1：
 *
 * 输入：s = "aacecaaa"
 * 输出："aaacecaaa"
 * 示例 2：
 *
 * 输入：s = "abcd"
 * 输出："dcbabcd"
 *
 *
 * 提示：
 *
 * 0 <= s.length <= 5 * 104
 * s 仅由小写英文字母组成
 */
public class Solution2 {
    public String shortestPalindrome(String s) {
        /*方法一滚动哈希
        int n = s.length();
        int base = 131, mod = 1000000007;
        int left = 0, right = 0, mul = 1;
        int best = -1;
        for (int i = 0; i < n; ++i) {
            left = (int) (((long) left * base + s.charAt(i)) % mod);
            right = (int) ((right + (long) mul * s.charAt(i)) % mod);
            if (left == right) {
                best = i;
            }
            mul = (int) ((long) mul * base % mod);
        }
        String add = (best == n - 1 ? "" : s.substring(best + 1));
        StringBuffer ans = new StringBuffer(add).reverse();
        ans.append(s);
        return ans.toString();*/


        /*方法二字符串匹配
        int len = s.length();
        StringBuilder stringBuilder = new StringBuilder();
        String str = stringBuilder.append(s).reverse().toString();
        for (int i = len; i >=0; i--) {
            if(s.substring(0,i).equals(str.substring(len-i))){
                return str.substring(0,len-i)+s;
            }
        }
        return null;*/


        //方法三KMP算法
        StringBuilder stringBuilder = new StringBuilder();
        String s1 = stringBuilder.append(s).reverse().toString();
        String str = s+"#"+s1;
        int len = str.length();
        int []next = new int[len];
        int j = 0;
        next[0] = j;
        for (int i = 1; i < len; i++) {
            while (j>0&&str.charAt(i)!=str.charAt(j)){
                j = next[j-1];
            }
            if(str.charAt(i)==str.charAt(j)){
                j++;
            }
            next[i]=j;
        }
        return new StringBuilder(s.substring(next[len-1],s.length())).reverse().toString()+s;
    }
}
